﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 报警信息管理窗体
    /// </summary>
    public partial class FormAlarm : HWFrmWithTitle
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormAlarm()
        {
            InitializeComponent();
        }
        private void FormAlarm_Load(object sender, EventArgs e)
        {
            InitColumns();
            LoadAlarms();
        }
        private void InitColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewAlarms, "Code", "报警代码", DataGridViewContentAlignment.MiddleCenter, 230);
            CommonHelper.CreateTextGridColumn(this.dataGridViewAlarms, "Name", "报警内容", DataGridViewContentAlignment.MiddleCenter, 530);
            CommonHelper.CreateTextGridColumn(this.dataGridViewAlarms, "Address", "PLC地址", DataGridViewContentAlignment.MiddleCenter, 230);
            this.dataGridViewAlarms.DoubleBufferedDataGirdView(true);
            this.dataGridViewAlarms.InitStyle();
        }
        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
        }
        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void LoadAlarms()
        {
            if (AlarmHelper.ALARM_HELPER == null)
            {
                HWMessageBox.Show(this, "报警帮助类未初始化");
                this.Close();
            }
            else
            {
                var alarms = AlarmHelper.ALARM_HELPER.GetAlarms();
                this.dataGridViewAlarms.Rows.Clear();
                foreach (var alarm in alarms)
                {
                    int rowIndex = this.dataGridViewAlarms.Rows.Add(1);
                    var row = this.dataGridViewAlarms.Rows[rowIndex];
                    row.Cells["Code"].Value = alarm.Code;
                    row.Cells["Name"].Value = alarm.Name;
                    row.Cells["Address"].Value = alarm.PLCAddress;
                    row.Tag = alarm;
                }
            }
        }
        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            new FormAlarmEdit(null).ShowDialog();
            LoadAlarms();
        }
        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            var selectedCells = this.dataGridViewAlarms.SelectedCells;
            if (selectedCells != null && selectedCells.Count > 0)
            {
                var row = this.dataGridViewAlarms.Rows[selectedCells[0].RowIndex];
                var alarm = (AlarmEntity)row.Tag;

                new FormAlarmEdit(alarm).ShowDialog();
                LoadAlarms();
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录再进行操作");
            }
        }
        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            var selectedCells = this.dataGridViewAlarms.SelectedCells;
            if (selectedCells != null && selectedCells.Count > 0)
            {
                if (HWMessageBox.ShowYesNo(this, "确认删除该记录吗？") == DialogResult.Yes)
                {
                    var row = this.dataGridViewAlarms.Rows[selectedCells[0].RowIndex];
                    var alarm = (AlarmEntity)row.Tag;
                    if (AlarmHelper.ALARM_HELPER.DeleteAlarm(alarm))
                    {
                        HWMessageBox.Show(this, "删除成功");
                    }
                    else
                    {
                        HWMessageBox.Show(this, "删除失败");
                    }
                    LoadAlarms();
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录再进行操作");
            }
        }
        private void dataGridViewUsers_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                var row = this.dataGridViewAlarms.Rows[e.RowIndex];
                var alarm = (AlarmEntity)row.Tag;

                new FormAlarmEdit(alarm).ShowDialog();
                LoadAlarms();
            }
        }
        private void FormAlarm_Shown(object sender, EventArgs e)
        {
        }
        private void FormAlarm_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
        private void buttonImport_Click(object sender, EventArgs e)
        {
            var dataTypeDialog = new FormDataType();
            dataTypeDialog.ShowDialog();
            var selectedDataType = dataTypeDialog.SelectedDataType;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*.xlsx|*.xlsx";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                CommonHelper.ShowWaiting(this, "正在导入数据，请稍候......");
                string filePath = openFileDialog.FileName;
                List<AlarmEntity> alarms = CommonHelper.ReadExcel<AlarmEntity>(filePath, (message) => { CommonHelper.ShowWaiting(this, message); });
                #region 修正
                if (alarms != null && alarms.Count > 0)
                {
                    foreach (var item in alarms)
                    {
                        item.DataType = selectedDataType;
                        switch (selectedDataType)
                        {
                            case EDataType.SHORT: item.StartValue = (short)1; item.EndValue = (short)0; break;
                            case EDataType.USHORT: item.StartValue = (ushort)1; item.EndValue = (ushort)0; break;
                            case EDataType.BOOL: item.StartValue = true; item.EndValue = false; break;
                            case EDataType.INT: item.StartValue = 1; item.EndValue = 0; break;
                            case EDataType.UINT: item.StartValue = (uint)1; item.EndValue = (uint)0; break;
                            case EDataType.FLOAT: item.StartValue = (float)1; item.EndValue = (float)0; break;
                            case EDataType.DOUBLE: item.StartValue = (double)1; item.EndValue = (double)0; break;
                        }
                    }
                }
                #endregion
                if (alarms != null && alarms.Count > 0)
                {
                    alarms.RemoveAll(v => string.IsNullOrWhiteSpace(v.PLCAddress) || string.IsNullOrWhiteSpace(v.Name) || string.IsNullOrWhiteSpace(v.Code));
                    AlarmHelper.ALARM_HELPER.UpdateAlarms(alarms);
                    LoadAlarms();
                    HWMessageBox.Show(this, "导入成功");
                }
                else
                {
                    HWMessageBox.Show(this, "没有合适的数据");
                }
            }
            CommonHelper.CloseWaiting();
        }
        private void buttonOutput_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xlsx|*.xlsx";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                CommonHelper.ShowWaiting(this, "正在导出数据，请稍候......");
                try
                {
                    bool outputResult = CommonHelper.WriteExcel(dialog.FileName, AlarmHelper.ALARM_HELPER.GetAlarms(), true,
                        "报警设置", (message) => { CommonHelper.ShowWaiting(this, message); }, true);
                    if (outputResult)
                    {
                        HWMessageBox.Show(this, "导出成功");
                        CommonHelper.OpenExcelFile(dialog.FileName);
                    }
                    else
                    {
                        HWMessageBox.Show(this, "导出失败");
                    }

                }
                catch (Exception ex)
                {
                    HWMessageBox.Show(this, ex.Message);
                    LogHelper.Error(ex);
                }
            }
            CommonHelper.CloseWaiting();
        }
    }
}
